from rest_framework import serializers
from django_celery_beat.models import PeriodicTask, CrontabSchedule


class ScheduleSerializer(serializers.ModelSerializer):
    connection = serializers.SerializerMethodField()

    def get_connection(self, instance):
        relation = instance.connection_tasks.select_related('connection__partner').first()
        if not relation:
            return None
        return {
            'id': relation.connection_id,
            'partner': {
                'id': relation.connection.partner.id,
                'name': relation.connection.partner.name
            }
        }

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        if instance.crontab:
            ret['crontab'] = CrontabScheduleSerializer(instance.crontab).data
        return ret

    class Meta:
        model = PeriodicTask
        fields = '__all__'


class CrontabScheduleSerializer(serializers.ModelSerializer):
    class Meta:
        model = CrontabSchedule
        exclude = ['id', 'timezone']
